#!/bin/bash
msg() {
    printf '%b\n' "$1" >&2
}

info()
{
    msg "[INFO] $1"
}

success() {
    msg "\e[1;32m[✔] ${1}${2} \33[0m "
}

notice() {
    msg "\e[1;33m ${1} \e[0m"
}

error_exit() {
    msg "\e[1;31m[✘] ${1}${2} \33[0m"
    exit 1
}

exec_cmd()
{
  echo "[执行命令] $1"
  $1
  if [ "$?" != "0" ]; then
    error_exit "命令执行失败: 错误码为 $?"
  fi
}

# sed匹配hosts.js内容，替换服务端环境
change_hosts() 
{
    if [ -f "hosts.js" ]; then
        case $build_type in 
            "dev")
                target_env="dev"
                echo "${work_palt}"/hosts.js
                sed -i "" "s/^const curr_env = .*/const curr_env = '$target_env'/" ${work_palt}"/hosts.js"
                info "切换到 ${target_env} 环境"
            ;;
            "prod")
                target_env="prod"
                echo "${work_palt}"/hosts.js
                sed -i "" "s/^const curr_env = .*/const curr_env = '$target_env'/" ${work_palt}"/hosts.js"
                info "切换到 ${target_env} 环境"
            ;;
        esac
        if [ "$?" != "0" ]; then
            error_exit "切换环境失败！"
        fi
    else
        error_exit "没有找到hosts.js文件！"
    fi
}

# 根据feature参数增加版本号，上传到微信小程序后台准备提审
# 用node程序直接读取version.js修改版本号
upload_for_release() 
{
    if [ -f ${work_palt}"/version.js" ]; then
        exec_cmd "node /Users/guang/.jenkins/workspace/xwsTest/upload.js ${work_palt} $feature $desc"
    else
        error_exit "没有找到version.js文件！"
    fi
}

# 生成开发版二维码
# 这里直接执行小程序cli的命令
uplaod_for_preview()
{
    exec_cmd "/Applications/wechatwebdevtools.app/Contents/Resources/app.nw/bin/cli -o"
    port=$(cat "/Users/guang/Library/Application Support/微信web开发者工具/Default/.ide")
    echo "微信开发者工具运行在${port}端口"
    echo "调用http://127.0.0.1:${port}/open"
    return_code=$(curl -sL -w %{http_code} http://127.0.0.1:${port} -o /open)
    if [ $return_code == 200 ]; then
        echo "返回状态码200，devtool启动成功！"
    else
    echo "返回状态码${return_code}，devtool启动失败"
        exit 1
    fi
  exec_cmd "pwd"
    exec_cmd "wget  -O  $BUILD_ID.png http://127.0.0.1:${port}/preview?projectpath=${work_palt}"
}

if [ "$build_type" == "dev" ]; then
  info "发布开发版！"
  change_hosts
  #生成二维码
  uplaod_for_preview
  success "预览成功！请扫描二维码进入开发版！"
elif [ "$build_type" == 'prod' ]; then
  info "准备上传！"
  change_hosts
  #提交代码微信公众平台
  upload_for_release
  success "上传成功！请到微信小程序后台设置体验版并提交审核！"
else
    error_exit "需要设置合法的build_type！"
fi